package com.senlan.water.controller.sys;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.senlan.water.common.constant.RedisConstant;
import com.senlan.water.common.exception.BusinessException;
import com.senlan.water.common.result.BaseResult;
import com.senlan.water.common.result.ResultCode;
import com.senlan.water.common.util.Md5Utils;
import com.senlan.water.dao.domain.User;
import com.senlan.water.dao.service.UserService;
import com.senlan.water.dto.sys.LoginDTO;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RBucket;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
@SaCheckLogin
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private Redisson redisson;

    /**
     * 登录
     * @param loginDTO
     * @return
     */
    @PostMapping("login")
    public BaseResult<SaTokenInfo> login(@RequestBody LoginDTO loginDTO) {
        //查询数据库拿到密码
        User user = userService.getUserByName(loginDTO.getUsername());
        if (user == null || StrUtil.isBlank(user.getUsername())){
            throw new BusinessException(ResultCode.USER_NOT_EXIST);
        }

        //验证密码正确性
        if(Md5Utils.md5WithSalt(loginDTO.getPassword()).equals(user.getPassword())) {
            StpUtil.login(user.getId());
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            log.info("当前登录的token信息：{}", JSONObject.toJSONString(tokenInfo));
            return BaseResult.data(tokenInfo);
        }
        return BaseResult.error(ResultCode.USER_CONNECT_LOGIN_ERROR);
    }

    /**
     * 登出
     * @return
     */
    @PostMapping("logout")
    public BaseResult<Boolean> logout(){
        StpUtil.logout();
        return BaseResult.success();
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("getUserInfo")
    public BaseResult<User> getUserInfo(){
        Long userId = StpUtil.getLoginIdAsLong();
        User user = userService.getById(userId);

        //redis存储用户信息
        RBucket<User> bucket = redisson.getBucket(RedisConstant.USER_INFO_PREFIX + userId);
        if (!bucket.isExists()){
            bucket.set(user, 30, TimeUnit.DAYS);
        }
        return BaseResult.data(user);
    }


}
